<template>
  <div>
    <van-nav-bar left-arrow @click="leftClick"></van-nav-bar>
    <div class="login-form">
      <h3 class="title">短信登录</h3>
      <van-form ref="form">
        <van-field
          placeholder="请输入手机号"
          v-model="form.mobile"
          name="mobile"
          :rules="rules.mobile"
        ></van-field>
        <van-field
          placeholder="请输入验证码"
          v-model="form.code"
          :rules="rules.code"
        >
          <template #button>
            <div class="code" @click="sendCode">
              发送验证码
            </div>
          </template>
        </van-field>
        <van-button class="btn" @click="submit">登录</van-button>
      </van-form>
    </div>
  </div>
</template>

<script>
import { authorizations } from '@/api/user.js'
export default {
  data () {
    return {
      form: {
        mobile: '13200000000',
        code: '246810'
      },
      rules: {
        mobile: [
          { required: true, message: '必填', trigger: 'onChange' },
          {
            validator: value => {
              const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              return reg.test(value)
            },
            message: '请输入之前手机号',
            trigger: 'onChange'
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'onChange' },
          {
            validator: value => {
              return value.length === 6
            },
            message: '请输入六位验证码',
            trigger: 'onChange'
          }
        ]
      }
    }
  },
  methods: {
    leftClick () {},
    submit () {
      this.$refs.form.validate().then(async () => {
        this.$toast.loading({ duration: 0 })
        const res = await authorizations(this.form)
        this.$store.commit('user/setToken', res.data.token)
        this.$router.push('/')
        this.$toast.success('验证成功')
        console.log('res:', res)
      })
      // .catch(() => {
      //   this.$toast.fail('验证失败')
      // })
    },
    sendCode () {
      this.$refs.form
        .validate('mobile')
        .then(() => {
          this.$toast.success('验证成功')
        })
        .catch(() => {
          this.$toast.fail('验证失败')
        })
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .van-nav-bar .van-icon {
  color: #999;
}
.login*form {
  padding: 20px;
}

.title {
  font-size: 18px;
  font-weight: 400;
  padding-left: 15px;
}

.code {
  font-size: 14px;
  color: #ccc;
}
.btn {
  width: 100%;
  background-color: #fd514a;
}
</style>
